import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './baseRouter'
import { getToken, clearSpecifiedLocalStorage } from '@/utils'
import { getAllMenuItem } from '@/utils'
// import {generateRoute } from '@/utils/router'
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { store } from '@/store';
import { cloneDeep, find } from 'lodash';
NProgress.configure({ showSpinner: false });

const whiteList = ['/login', '/404']

const router = createRouter({
  history: createWebHashHistory(""),
  routes,
});

router.beforeEach((to, from, next) => {
  const token = getToken()
  const menus = localStorage.getItem('menu') ? JSON.parse(localStorage.getItem('menu')) : []
  const { tabs } = store.state.setting

  NProgress.start();
  // console.log(to.path, '----to.path----');
  if (whiteList.includes(to.path)) {
    next()
  } else {
    if (!token) {
      clearSpecifiedLocalStorage()
      store.commit('updateState', {
        tabs: [],
        activeFirstMenu: null,
        activeFirstMenuName: null,
        subMenu: [],
        activeSideMenu: null,
      })
      next({ path: '/login', query: { refresh: Math.random() } })
    } else {
      const selectMenu = getAllMenuItem(menus, to.path)
      if (!selectMenu) {
        if (process.env.VUE_APP_CONFIG == 'online') {
          if (to.path === '/makeManage/makeList') {
            store.commit('updateState', {
              activeSideMenu: ['/makeManage/makeList'],
            })
          }
        } else {
          if (to.path === '/hangManage/prodTimeInfo') {
            store.commit('updateState', {
              activeSideMenu: ['/hangManage/prodTimeInfo'],
            })
          }
        }
        next()
        // router.replace('/404')
      } else {
        const levelOne = selectMenu[selectMenu.length - 1]
        const ntabs = cloneDeep(tabs)
        if (!find(ntabs, (item) => item.path == selectMenu[0].path)) {
          ntabs.push({ ...selectMenu[0], query: to.query })
        }

        store.commit('updateState', {
          subMenu: levelOne.children,
          activeFirstMenu: [levelOne.path],
          activeFirstMenuName: `menu.${levelOne.permission}`,
          activeSideMenu: [selectMenu[0].path],
          tabs: ntabs
        })
        next()
      }
    }
  }
  NProgress.done();
})

// 路由加载后
router.afterEach(() => {
  NProgress.done();
});
export default router;
